package indvi.cfeng.persistencedemo.config;


import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.util.Collection;
import java.util.Collections;

/**
 * @author Cfeng
 * @date 2022/7/17
 */
@Configuration
public class MongoConfig  {

    @Value("${spring.data.mongodb.host}")
    private String host;

    //host和port没有用上
    @Value("${spring.data.mongodb.database}")
    private String database;

    @Value("${spring.data.mongodb.port}")
    private Integer port;

    @Value("${spring.data.mongodb.uri}")
    private String uri;
//    使用配置类的方式，继承AbstractMongoClientConfiguration
//    @Override
//    protected String getDatabaseName() {
//        return database;
//    }
//
//    @Override
//    //使用uri创建ConnectionString，创建MongoClientSettings从而创建MongoClient【利用MongoClients工具类】
//    public MongoClient mongoClient() {
//        ConnectionString connectionString = new ConnectionString(uri);
//        //连接的uri创建Mongo客户端设置
//        MongoClientSettings mongoClientSettings = MongoClientSettings.builder().applyConnectionString(connectionString).build();
//        return MongoClients.create(mongoClientSettings);
//    }
//
//    //获得映射所在的包的集合
//    @Override
//    protected Collection<String> getMappingBasePackages() {
//        return Collections.singleton("indvi.cfeng.persistencedemo");
//    }
    @Bean
    public MongoClient mongoClient() {
        ConnectionString connectionString = new ConnectionString(uri);
        //连接的uri创建Mongo客户端设置
        MongoClientSettings mongoClientSettings = MongoClientSettings.builder().applyConnectionString(connectionString).build();
        return MongoClients.create(mongoClientSettings);
    }
    //再创建MongoTemplate对象 【redisTemplate对象如果是Lettuce是自动配置了的，但是不管Lettuce还是Jedis可以手动配置修改参数】
    //使用上面的客户端和数据库名
    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(this.mongoClient(),database);
    }
}
